package oldServlets;

import model.*;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class FirstServlet
 */
@WebServlet(urlPatterns = { "/FirstServlet" }, initParams = {
		@WebInitParam(name = "val1", value = "7"),
		@WebInitParam(name = "val2", value = "3") })
public class FirstServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private String var1;
	private String var2;

	EntityManagerFactory emf;
	EntityManager em;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public FirstServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */

	public void init() {
		ServletConfig config = getServletConfig();

		var1 = config.getInitParameter("val1");
		var2 = config.getInitParameter("val2");

		emf = Persistence.createEntityManagerFactory("ServletTest");
		em = emf.createEntityManager();
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		response.setContentType("text/html");

		String numele = request.getParameter("input1");

		String materia = request.getParameter("input2");

		PrintWriter out = response.getWriter();
	
		
		List<Nota> notes = em
				.createQuery(
						"select n from Nota n where n.student.nume= :vnume and n.materie.denumire= :vmat")
				.setParameter("vnume", numele).setParameter("vmat", materia)
				.getResultList();

		out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 "
				+ "Transitional//EN\">");

		out.println("<html>");
		out.println("<body bgcolor=\"#F3FBFE\">");
		out.println("<head>");
		out.println("<title>" + "You have executed a simple servlet!"
				+ "</title>");
		out.println("</head>");
		out.println("<body>");
		out.println("<h1>" + "SIMPLE SERVLET " + " " + var1 + " " + var2 + "  "
				+ numele + "</h1> ");

		for (Nota temp : notes) {
			out.println("<h1>" + temp + "</h1>");
		}
		out.println("</body>");
		out.println("</html>");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		doGet(request, response);
	}

}
